<template>
    <el-form @submit.native.prevent :inline="true" :model="listQuery" ref="queryForm" class="demo-form-inline">
        <el-form-item label="用户id" prop="userId">
            <el-input v-model="listQuery.userId" placeholder="用户id" />
        </el-form-item>
        <el-form-item label="用户名" prop="username">
            <el-input v-model="listQuery.username" placeholder="用户名" />
        </el-form-item>
        <el-form-item label="昵称" prop="nickname">
            <el-input v-model="listQuery.nickname" placeholder="昵称" />
        </el-form-item>
        <el-form-item label="手机" prop="telNumber">
            <el-input v-model="listQuery.telNumber" placeholder="手机" />
        </el-form-item>
        <el-form-item label="状态" prop="disabled">
            <el-select v-model="listQuery.disabled" placeholder="状态">
                <el-option label="禁用" :value="true" />
                <el-option label="启用" :value="false" />
            </el-select>
        </el-form-item>
        <el-row>
            <el-form-item>
                <el-button :disabled="tableLoading" type="primary" @click="showInsertDialog">新增</el-button>
                <el-button :disabled="tableLoading" type="primary" native-type="submit"
                    @click="submitQueryList(queryForm)">查询</el-button>
                <el-button :disabled="tableLoading" @click="resetForm(queryForm)">重置</el-button>
            </el-form-item>
        </el-row>

    </el-form>

    <el-table v-loading="tableLoading" :data="userList" style="width: 100%" border>
        <el-table-column prop="userId" label="用户id" align="center" />
        <el-table-column prop="nickname" label="昵称" align="center" />
        <el-table-column prop="username" label="用户名" align="center" />
        <el-table-column prop="telNumber" label="手机" align="center" />
        <el-table-column prop="remark" label="备注" align="center" />
        <el-table-column prop="disabled" label="状态" align="center">
            <template #default="scope">
                <el-tag :type="scope.row.disabled ? 'danger' : 'success'" disable-transitions>{{ scope.row.disabled ? '禁用' :
                    '启用' }}</el-tag>
            </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="200" align="center">
            <template #default="scope">
                <el-button link type="primary" size="small" @click="showDetailDialog(scope.row)">查看</el-button>
                <el-button link type="primary" size="small" @click="showEditDialog(scope.row)">编辑</el-button>
                <el-button link type="primary" size="small" @click="showRestPasswordDialog(scope.row)">重置密码</el-button>
                <el-button link :type="scope.row.disabled ? 'success' : 'danger'" size="small"
                    @click="showUpdateDisabaledDialog(scope.row)">{{ scope.row.disabled ? '启用' : '禁用' }}
                </el-button>
                <el-button link type="danger" size="small" @click="showDeleteDialog(scope.row)">删除</el-button>
            </template>
        </el-table-column>
    </el-table>

    <el-pagination :page-count="pageInfo.pageCount" :page-size="pageInfo.pageSize" :current-page="pageInfo.currentPage"
        :total="pageInfo.pageTotal" @size-change="handleSizeChange" @current-change="handleCurrentChange" background
        layout="total,sizes,prev,pager,next,jumper,->"></el-pagination>

    <el-dialog v-model="detailFormVisible" :title="isEdit ? '修改用户信息' : '查看用户信息'" width="300px" center>
        <el-form :model="currentEntity">
            <el-form-item label="用户id" prop="userId" label-width="100px" disabled>
                <el-input v-model="currentEntity.userId" autocomplete="off" disabled />
            </el-form-item>
            <el-form-item label="用户名" prop="username" label-width="100px">
                <el-input v-model="currentEntity.username" autocomplete="off" />
            </el-form-item>
            <el-form-item label="昵称" prop="nickname" label-width="100px">
                <el-input v-model="currentEntity.nickname" autocomplete="off" />
            </el-form-item>
            <el-form-item label="手机" prop="telNumber" label-width="100px">
                <el-input v-model="currentEntity.telNumber" autocomplete="off" />
            </el-form-item>
            <el-form-item label="备注" prop="remark" label-width="100px">
                <el-input v-model="currentEntity.remark" autocomplete="off" />
            </el-form-item>
            <el-form-item label="状态" prop="disabled" label-width="100px">
                <el-select v-model="currentEntity.disabled">
                    <el-option label="禁用" :value="true" />
                    <el-option label="启用" :value="false" />
                </el-select>
            </el-form-item>
            <el-form-item label="角色" prop="roleIdList" label-width="100px">
                <el-select v-model="currentEntity.roleIdList" :multiple="true">
                    <el-option v-for="role in roleList" :key="role.roleId" :label="role.roleName" :value="role.roleId" />
                </el-select>
            </el-form-item>

        </el-form>
        <template #footer v-if="isEdit">
            <span class="dialog-footer">
                <el-button @click="detailFormVisible = false">取消</el-button>
                <el-button type="primary" @click="handleUpdate">
                    确定
                </el-button>
            </span>
        </template>
    </el-dialog>


    <el-dialog v-model="insertFormVisible" title="系统用户新增" width="300px" center>
        <el-form :model="currentEntity" :rules="insertFormRuleList" ref="insertForm">
            <el-form-item label="用户名" prop="username" label-width="100px">
                <el-input v-model="currentEntity.username" autocomplete="off" />
            </el-form-item>
            <el-form-item label="密码" prop="password" label-width="100px">
                <el-input v-model="currentEntity.password" autocomplete="off" type="password" show-password />
            </el-form-item>
            <el-form-item label="昵称" prop="nickname" label-width="100px">
                <el-input v-model="currentEntity.nickname" autocomplete="off" />
            </el-form-item>
            <el-form-item label="手机" prop="telNumber" label-width="100px">
                <el-input v-model="currentEntity.telNumber" autocomplete="off" />
            </el-form-item>
            <el-form-item label="备注" prop="remark" label-width="100px">
                <el-input v-model="currentEntity.remark" autocomplete="off" />
            </el-form-item>
            <el-form-item label="禁用状态" prop="disabled" label-width="100px">
                <el-select v-model="currentEntity.disabled">
                    <el-option label="禁用" :value="true" />
                    <el-option label="启用" :value="false" />
                </el-select>
            </el-form-item>
            <el-form-item label="角色" prop="roleIdList" label-width="100px">
                <el-select v-model="currentEntity.roleIdList" :multiple="true">
                    <el-option v-for="role in roleList" :key="role.roleId" :label="role.roleName" :value="role.roleId" />
                </el-select>
            </el-form-item>

        </el-form>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="insertFormVisible = false">Cancel</el-button>
                <el-button type="primary" @click="handleInsert(insertForm)">
                    Confirm
                </el-button>
            </span>
        </template>
    </el-dialog>
</template>

<script setup lang="ts" >
import { ElMessage, ElMessageBox, FormInstance, FormRules } from "element-plus";
import { reactive, ref, watch } from "vue";
import * as requestApi from "@/api/SystemUserApi"
import * as roleApi from "@/api/RoleApi"
import { SystemUser } from "@/domain/entity/SystemUser";
import { UserInfoListQuery } from "@/domain/query/UserInfoListQuery";
import { PageInfo } from "@/domain/entity/PageInfo";
import { Role } from "@/domain/entity/Role";

// 当前操作对象信息
const currentEntity: SystemUser = reactive<SystemUser>(new SystemUser())

// 监听当前用户角色变化
watch(() => currentEntity.roleList!, (roleList: Array<Role>) => {
    if (!!roleList) {
        currentEntity.roleIdList!.length! = 0;
        roleList.forEach((role, index) => {
            currentEntity.roleIdList!.push(role.roleId!);
        });
    }
});

// 角色列表
const roleList: Array<Role> = reactive<Array<Role>>(new Array());

// 新增用户表单
const insertForm = ref<FormInstance>();

// 新增用户表单规则
const insertFormRuleList = reactive<FormRules>({
    username: [
        { required: true, message: '[username] 不可为空', trigger: 'blur' },
    ],
    password: [
        { required: true, message: '[password] 不可为空', trigger: 'blur' },
    ],
    nickname: [
        { required: true, message: '[nickname] 不可为空', trigger: 'blur' },
    ],
})

//////////////////////  查询   ///////////////////////

// 查询条件
const listQuery = reactive<UserInfoListQuery>(new UserInfoListQuery());
// 查询表单
const tableLoading = ref(false);
const queryForm = ref<FormInstance>()
// 详情表单
const detailFormVisible = ref(false)
const isEdit = ref(false);
// 新增表单
const insertFormVisible = ref(false)

/**
 * 提交查询表单
 * @param queryFormInstance 查询表单对象
 */
const submitQueryList = (queryFormInstance: FormInstance | undefined) => {
    if (!queryFormInstance) return;
    updateTable();
}

/**
 * 重置查询表单
 * @param queryFormInstance 查询表单对象
 */
const resetForm = (queryFormInstance: FormInstance | undefined) => {
    if (!queryFormInstance) return;
    queryFormInstance.resetFields()
}



//////////////////////  处理   ///////////////////////

/**
 * 更新角色列表
 */
const updateRoleList = () => {
    roleApi.getList().then(response => {
        roleList.length = 0;
        roleList.push(...response.data.data!);
    });
}




/**
 * 展示用户新增对话框
 */
const showInsertDialog = () => {
    Object.assign(currentEntity, new SystemUser());
    currentEntity.disabled = false;
    currentEntity.roleIdList = new Array;
    currentEntity.roleList = new Array;
    
    insertFormVisible.value = true;
    updateRoleList();

}

/**
 * 展示用户详情对话框
 * @param row 行数据
 */
const showDetailDialog = (row: SystemUser) => {
    isEdit.value = false;
    Object.assign(currentEntity, new SystemUser());
    Object.assign(currentEntity, row);
    detailFormVisible.value = true;

    requestApi.getDetail(currentEntity.userId!).then(response => {
        Object.assign(currentEntity, response.data.data);
    });

    updateRoleList();
}

/**
 * 展示编辑对话框
 * @param row 行数据
 */
const showEditDialog = (row: SystemUser) => {
    isEdit.value = true;
    Object.assign(currentEntity, new SystemUser());
    Object.assign(currentEntity, row);

    requestApi.getDetail(currentEntity.userId!).then(response => {
        Object.assign(currentEntity, response.data.data);
    });

    detailFormVisible.value = true;
    updateRoleList();
}

/**
 * 展示删除对话框
 * @param row 行数据
 */
const showDeleteDialog = (row: SystemUser) => {
    Object.assign(currentEntity, new SystemUser());
    Object.assign(currentEntity, row);
    ElMessageBox.confirm(
        `确定删除: ${currentEntity.username}(${currentEntity.userId}) ?`,
        '确定删除',
        {
            confirmButtonText: 'OK',
            cancelButtonText: 'Cancel',
            type: 'warning',
        }
    )
        .then(() => {
            handleDelete(currentEntity.userId!)
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: 'Delete canceled',
            })
        })
}

/**
 * 展示禁用对话框
 * @param row 行数据
 */
const showUpdateDisabaledDialog = (row: SystemUser) => {
    Object.assign(currentEntity, new SystemUser());
    Object.assign(currentEntity, row);
    ElMessageBox.confirm(
        `切换禁用状态: ${currentEntity.username}(${currentEntity.userId}) ?`,
        '切换禁用状态',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(() => {
            handleUpdateDisabled(currentEntity.userId!)
        })

}

/**
 * 展示重置密码对话框
 * @param row 当前用户数据row
 */
const showRestPasswordDialog = (row: SystemUser) => {
    Object.assign(currentEntity, new SystemUser());
    Object.assign(currentEntity, row);
    ElMessageBox.confirm(
        `切换禁用状态: ${currentEntity.username}(${currentEntity.userId}) ?`,
        '切换禁用状态',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(() => {
            handleResetPassword(currentEntity.userId!)
        })
        .catch(() => {
            ElMessage.info("取消");
        })
}


/**
 * 删除
 * @param userId 用户id
 */
const handleDelete = (userId: string) => {
    requestApi.requestDelete(userId).then(response => {

        if (response.data.code === 0) {
            ElMessage.success('删除成功')
            updateTable();
        } else {
            ElMessage.warning('删除失败')
        }

    });
}

/**
 * 更新禁用状态
 * @param userId 用户id
 */
const handleUpdateDisabled = (userId: string) => {
    requestApi.requestUpdateDisabled(userId).then(response => {

        if (response.data.code === 0) {
            ElMessage.success('更新成功')
            updateTable();
        } else {
            ElMessage.warning('更新失败')
        }

    });
}

/**
 * 重置密码
 * @param userId 用户id
 */
const handleResetPassword = (userId: string) => {
    requestApi.requestResetPassowrd(userId).then(response => {

        if (response.data.code === 0) {
            ElMessage.success('重置完成')
        } else {
            ElMessage.warning('重置出错')
        }

    });
}



/**
 * 更新
 */
const handleUpdate = () => {
    requestApi.requestUpdate(currentEntity).then(response => {
        let responseUser = response.data.data
        Object.assign(currentEntity, new SystemUser());
        Object.assign(currentEntity, responseUser);
        updateTable();
        detailFormVisible.value = false;
    });
}

/**
 * 处理用户新增
 * @param formInstance 新增表单
 * 
 */
const handleInsert = (formInstance: FormInstance | undefined) => {
    if (!formInstance) return;
    formInstance.validate((valid, fields) => {
        if (valid) {
            requestApi.requestInsert(currentEntity).then(response => {
                let responseUser = response.data.data
                Object.assign(currentEntity, new SystemUser());
                Object.assign(currentEntity, responseUser);
                updateTable();
                insertFormVisible.value = false;
            });
        } else {
            ElMessage.warning("请填写必填项")
        }
    })
}

//////////////////////  列表   ///////////////////////

/**
 * 更新列表展示
 */
// 用户列表
const userList: Array<SystemUser> = reactive([]);
const updateTable = () => {
    tableLoading.value = true;
    requestApi.getListPage(listQuery).then(response => {
        let list: Array<SystemUser> = response.data.data!.records!;
        userList.length = 0;
        userList.push(...list)
        pageInfo.pageCount = response.data.data?.pages!;
        pageInfo.pageSize = response.data.data?.size!;
        pageInfo.pageTotal = response.data.data?.total!;
        pageInfo.currentPage = response.data.data?.current!;
    }).finally(() => {
        tableLoading.value = false;
    });
}

//////////////////////  分页处理   ///////////////////////
// 分页信息
const pageInfo: PageInfo = reactive<PageInfo>(new PageInfo())
// 侦听页面大小改变,触发table刷新
watch(() => pageInfo.pageSize, (val) => {
    listQuery.size = val;
    updateTable()
})
// 侦听当前页码改变,触发table刷新
watch(() => pageInfo.currentPage, (val) => {
    listQuery.current = val;
    updateTable()
})
// 分页插件处理事件
const handleSizeChange = (val: number) => {
    pageInfo.pageSize = val;
}
const handleCurrentChange = (val: number) => {
    pageInfo.currentPage = val
}

//////////////////////  分页处理   ///////////////////////

// 加载完毕获取列表
updateTable();

</script>


<style scoped>
.el-pagination {
    margin-top: 20px;
    text-align: center;
}
</style>
